<template>
  <div class="main-layout">
    <!-- 顶部导航栏 -->
    <el-header class="top-header">
      <div class="header-left">
        <div class="logo">
          <el-icon size="24" color="#409EFF">
            <Monitor />
          </el-icon>
          <span class="logo-text">公共卫生体检系统</span>
          <span class="subtitle">Public health examination system</span>
        </div>
      </div>
      
      <!-- 一级菜单 -->
      <div class="top-menu">
        <el-menu
          :default-active="activeTopMenu"
          mode="horizontal"
          @select="handleTopMenuSelect"
          class="top-nav-menu"
        >
          <el-menu-item
            v-for="item in topMenuItems"
            :key="item.key"
            :index="item.key"
          >
            <el-icon><component :is="item.icon" /></el-icon>
            <span>{{ item.title }}</span>
          </el-menu-item>
        </el-menu>
      </div>

      <div class="header-right">
        <!-- 用户信息下拉菜单 -->
        <el-dropdown @command="handleCommand">
          <span class="user-info">
            <el-avatar :size="32" class="user-avatar">
              <el-icon><User /></el-icon>
            </el-avatar>
            <span class="username">{{ userInfo.fullName || userInfo.username }}</span>
            <el-icon class="el-icon--right"><ArrowDown /></el-icon>
          </span>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="profile">
                <el-icon><Setting /></el-icon>
                个人资料
              </el-dropdown-item>
              <el-dropdown-item command="changePassword">
                <el-icon><Key /></el-icon>
                修改密码
              </el-dropdown-item>
              <el-dropdown-item divided command="logout">
                <el-icon><SwitchButton /></el-icon>
                退出登录
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </el-header>

    <!-- 主体内容区域 -->
    <el-container class="main-container">
      <!-- 左侧二级菜单 -->
      <el-aside :width="isCollapse ? '64px' : '200px'" class="sidebar">
        <div class="sidebar-header">
          <el-button
            type="text"
            @click="toggleSidebar"
            class="collapse-btn"
          >
            <el-icon size="20">
              <Expand v-if="isCollapse" />
              <Fold v-else />
            </el-icon>
          </el-button>
          <span v-if="!isCollapse" class="sidebar-title">{{ currentTopMenuTitle }}</span>
        </div>
        
        <el-menu
          :default-active="activeMenu"
          :collapse="isCollapse"
          :unique-opened="true"
          router
          class="sidebar-menu"
        >
          <el-menu-item
            v-for="item in currentSubMenuItems"
            :key="item.path"
            :index="item.path"
            :disabled="!hasPermission(item.roles)"
          >
            <el-icon><component :is="item.icon" /></el-icon>
            <template #title>{{ item.title }}</template>
          </el-menu-item>
        </el-menu>
      </el-aside>

      <!-- 主内容区域 -->
      <el-main class="main-content">
        <div class="content-header">
          <el-breadcrumb separator="/" class="breadcrumb">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item v-if="currentTopMenuTitle">{{ currentTopMenuTitle }}</el-breadcrumb-item>
            <el-breadcrumb-item v-if="currentRoute.meta.title">{{ currentRoute.meta.title }}</el-breadcrumb-item>
          </el-breadcrumb>
        </div>
        
        <div class="content-body">
          <router-view v-slot="{ Component }">
            <transition name="fade-transform" mode="out-in">
              <component :is="Component" />
            </transition>
          </router-view>
        </div>
      </el-main>
    </el-container>

    <!-- 修改密码对话框 -->
    <el-dialog
      v-model="showPasswordDialog"
      title="修改密码"
      width="400px"
      :before-close="handleClosePasswordDialog"
    >
      <el-form
        ref="passwordFormRef"
        :model="passwordForm"
        :rules="passwordRules"
        label-width="80px"
      >
        <el-form-item label="旧密码" prop="oldPassword">
          <el-input
            v-model="passwordForm.oldPassword"
            type="password"
            show-password
            placeholder="请输入旧密码"
          />
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input
            v-model="passwordForm.newPassword"
            type="password"
            show-password
            placeholder="请输入新密码"
          />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
            v-model="passwordForm.confirmPassword"
            type="password"
            show-password
            placeholder="请再次输入新密码"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleClosePasswordDialog">取消</el-button>
          <el-button type="primary" @click="handleChangePassword" :loading="passwordLoading">
            确认修改
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useUserStore } from '@/store/user.store'

const route = useRoute()
const router = useRouter()
const userStore = useUserStore()

// 响应式数据
const isCollapse = ref(false)
const showPasswordDialog = ref(false)
const passwordLoading = ref(false)
const passwordFormRef = ref()
const activeTopMenu = ref('archives')

// 密码表单
const passwordForm = ref({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 密码验证规则
const passwordRules = {
  oldPassword: [
    { required: true, message: '请输入旧密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== passwordForm.value.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 计算属性
const currentRoute = computed(() => route)
const activeMenu = computed(() => route.path)
const userInfo = computed(() => userStore.userInfo || {})

// 顶级菜单配置（严格按照截图）
const topMenuItems = ref([
  {
    key: 'archives',
    title: '档案管理',
    icon: 'UserFilled'
  },
  {
    key: 'checkup',
    title: '体检管理',
    icon: 'Monitor'
  },
  {
    key: 'statistics',
    title: '统计管理',
    icon: 'DataAnalysis'
  },
  {
    key: 'department',
    title: '科室管理',
    icon: 'OfficeBuilding'
  },
  {
    key: 'package',
    title: '体检套餐',
    icon: 'Box'
  },
  {
    key: 'system',
    title: '系统管理',
    icon: 'Setting'
  }
])

// 二级菜单配置
const subMenuConfig = {
  archives: [
    {
      path: '/archives/personal',
      title: '个人档案管理',
      icon: 'User'
    },
    {
      path: '/archives/group',
      title: '团体档案管理',
      icon: 'UserFilled'
    },
    {
      path: '/archives/search',
      title: '档案查询',
      icon: 'Search'
    }
  ],
  checkup: [
    {
      path: '/checkup/appointment',
      title: '预约管理',
      icon: 'Calendar'
    },
    {
      path: '/checkup/entry',
      title: '体检录入',
      icon: 'EditPen'
    },
    {
      path: '/checkup/process',
      title: '体检流程',
      icon: 'Connection'
    },
    {
      path: '/checkup/report',
      title: '报告管理',
      icon: 'Document'
    },
    {
      path: '/checkup/review',
      title: '报告审核',
      icon: 'View'
    }
  ],
  statistics: [
    {
      path: '/statistics/overview',
      title: '统计概览',
      icon: 'DataBoard'
    },
    {
      path: '/statistics/analysis',
      title: '数据分析',
      icon: 'TrendCharts'
    },
    {
      path: '/statistics/export',
      title: '数据导出',
      icon: 'Download'
    }
  ],
  department: [
    {
      path: '/department/manage',
      title: '科室管理',
      icon: 'OfficeBuilding'
    },
    {
      path: '/department/staff',
      title: '人员管理',
      icon: 'Avatar'
    },
    {
      path: '/department/equipment',
      title: '设备管理',
      icon: 'Monitor'
    }
  ],
  package: [
    {
      path: '/package/manage',
      title: '套餐管理',
      icon: 'Box'
    },
    {
      path: '/package/items',
      title: '检查项目',
      icon: 'List'
    },
    {
      path: '/package/pricing',
      title: '价格管理',
      icon: 'Money'
    }
  ],
  system: [
    {
      path: '/system/users',
      title: '用户管理',
      icon: 'User',
      roles: ['admin']
    },
    {
      path: '/system/roles',
      title: '角色管理',
      icon: 'UserFilled',
      roles: ['admin']
    },
    {
      path: '/system/config',
      title: '系统配置',
      icon: 'Setting',
      roles: ['admin']
    },
    {
      path: '/system/logs',
      title: '操作日志',
      icon: 'Document',
      roles: ['admin']
    }
  ]
}

// 当前顶级菜单标题
const currentTopMenuTitle = computed(() => {
  const item = topMenuItems.value.find(item => item.key === activeTopMenu.value)
  return item ? item.title : ''
})

// 当前二级菜单项
const currentSubMenuItems = computed(() => {
  return subMenuConfig[activeTopMenu.value] || []
})

// 方法
const toggleSidebar = () => {
  isCollapse.value = !isCollapse.value
}

const hasPermission = (roles) => {
  if (!roles || roles.length === 0) return true
  return roles.includes(userInfo.value.role)
}

const handleTopMenuSelect = (key) => {
  activeTopMenu.value = key
  // 跳转到对应模块的第一个子菜单
  const subItems = subMenuConfig[key]
  if (subItems && subItems.length > 0) {
    router.push(subItems[0].path)
  }
}

const handleCommand = (command) => {
  switch (command) {
    case 'profile':
      router.push('/profile')
      break
    case 'changePassword':
      showPasswordDialog.value = true
      break
    case 'logout':
      handleLogout()
      break
  }
}

const handleLogout = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要退出登录吗？',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    userStore.logout()
    router.push('/login')
    ElMessage.success('已退出登录')
  } catch {
    // 用户取消
  }
}

const handleChangePassword = async () => {
  try {
    await passwordFormRef.value.validate()
    passwordLoading.value = true
    
    await userStore.changePassword({
      oldPassword: passwordForm.value.oldPassword,
      newPassword: passwordForm.value.newPassword,
      confirmPassword: passwordForm.value.confirmPassword
    })
    
    ElMessage.success('密码修改成功')
    handleClosePasswordDialog()
  } catch (error) {
    console.error('修改密码失败:', error)
  } finally {
    passwordLoading.value = false
  }
}

const handleClosePasswordDialog = () => {
  showPasswordDialog.value = false
  passwordForm.value = {
    oldPassword: '',
    newPassword: '',
    confirmPassword: ''
  }
  passwordFormRef.value?.resetFields()
}

// 根据当前路由自动设置顶级菜单
const updateActiveTopMenu = () => {
  const path = route.path
  for (const [key, items] of Object.entries(subMenuConfig)) {
    if (items.some(item => path.startsWith(item.path))) {
      activeTopMenu.value = key
      break
    }
  }
}

// 监听路由变化
watch(() => route.path, () => {
  updateActiveTopMenu()
}, { immediate: true })

// 生命周期
onMounted(() => {
  // 获取当前用户信息
  if (!userInfo.value.id) {
    userStore.getCurrentUser()
  }
  updateActiveTopMenu()
})
</script>

<style scoped>
.main-layout {
  height: 100vh;
  display: flex;
  flex-direction: column;
}

/* 顶部导航栏 */
.top-header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 20px;
  height: 60px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.header-left {
  display: flex;
  align-items: center;
}

.logo {
  display: flex;
  align-items: center;
  margin-right: 40px;
}

.logo-text {
  font-size: 20px;
  font-weight: bold;
  margin-left: 8px;
  margin-right: 8px;
}

.subtitle {
  font-size: 12px;
  opacity: 0.8;
  margin-left: 8px;
}

.top-menu {
  flex: 1;
  display: flex;
  justify-content: center;
}

.top-nav-menu {
  background: transparent;
  border-bottom: none;
}

.top-nav-menu .el-menu-item {
  color: white;
  border-bottom: 2px solid transparent;
  margin: 0 10px;
  padding: 0 15px;
  font-size: 16px;
  font-weight: 500;
  transition: all 0.3s ease;
}

.top-nav-menu .el-menu-item:hover {
  background-color: rgba(255, 255, 255, 0.2);
  border-bottom-color: rgba(255, 255, 255, 0.8);
  color: #f0f8ff;
  transform: translateY(-1px);
}

.top-nav-menu .el-menu-item.is-active {
  background-color: rgba(255, 255, 255, 0.15);
  border-bottom-color: white;
  color: white;
  font-weight: 600;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}

.header-right {
  display: flex;
  align-items: center;
}

.user-info {
  display: flex;
  align-items: center;
  cursor: pointer;
  padding: 8px 12px;
  border-radius: 4px;
  transition: background-color 0.3s;
}

.user-info:hover {
  background-color: rgba(255, 255, 255, 0.1);
}

.user-avatar {
  margin-right: 8px;
}

.username {
  margin-right: 8px;
  font-size: 14px;
}

/* 主体容器 */
.main-container {
  flex: 1;
  display: flex;
}

/* 侧边栏 */
.sidebar {
  background-color: #f8f9fa;
  border-right: 1px solid #e4e7ed;
  transition: width 0.3s;
  overflow: hidden;
}

.sidebar-header {
  height: 50px;
  display: flex;
  align-items: center;
  padding: 0 15px;
  border-bottom: 1px solid #e4e7ed;
  background-color: white;
}

.collapse-btn {
  margin-right: 10px;
  font-size: 18px;
}

.sidebar-title {
  font-size: 16px;
  font-weight: bold;
  color: #303133;
}

.sidebar-menu {
  border-right: none;
  background-color: #f8f9fa;
}

.sidebar-menu .el-menu-item {
  color: #606266;
}

.sidebar-menu .el-menu-item:hover {
  background-color: #ecf5ff;
  color: #409EFF;
}

.sidebar-menu .el-menu-item.is-active {
  background-color: #409EFF;
  color: white;
}

/* 主内容区域 */
.main-content {
  background-color: #f5f7fa;
  padding: 0;
  overflow-y: auto;
}

.content-header {
  background-color: white;
  padding: 15px 20px;
  border-bottom: 1px solid #e4e7ed;
  box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
}

.breadcrumb {
  font-size: 14px;
}

.content-body {
  padding: 20px;
}

/* 页面切换动画 */
.fade-transform-enter-active,
.fade-transform-leave-active {
  transition: all 0.3s;
}

.fade-transform-enter-from {
  opacity: 0;
  transform: translateX(30px);
}

.fade-transform-leave-to {
  opacity: 0;
  transform: translateX(-30px);
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .logo-text {
    font-size: 16px;
  }
  
  .subtitle {
    display: none;
  }
}

@media (max-width: 768px) {
  .top-header {
    padding: 0 10px;
  }
  
  .logo {
    margin-right: 20px;
  }
  
  .top-nav-menu .el-menu-item {
    margin: 0 5px;
    padding: 0 10px;
  }
  
  .content-body {
    padding: 10px;
  }
  
  .breadcrumb {
    display: none;
  }
}
</style>